﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Netra
{
    partial class CreateTradeRouteForm : Form // ROTFL LOL
    {

        static int planet_col_idx=0;
        static int free_space_col_idx = 1;
        static int first_ware_col_idx = 2;

        int cargo_space;

        private Galaxy galaxy;

        private TradeRoute trade_route;

        public CreateTradeRouteForm(Galaxy _galaxy,TradeRoute _trade_route)
        {
            InitializeComponent();

            cargo_space = 10;

            galaxy = _galaxy;
            trade_route = _trade_route;


            //merch_listBox.DataSource = ware_list;
            merch_listBox.DataSource = Merch.Goods;
            merch_listBox.DisplayMember = "Name";
            merch_listBox.ValueMember = "Name";

            PopulateTable();

        }

        void PopulateTable()
        {
            trade_list_view.AutoGenerateColumns = false;
            //foreach(Planet planet in 
            DataGridViewComboBoxColumn planet_column = new DataGridViewComboBoxColumn();
            {
                //planet_column.DataPropertyName = ColumnName.TitleOfCourtesy.ToString();
                planet_column.HeaderText = "Planet";
                planet_column.Name = "Planet";
                planet_column.DropDownWidth = 160;
                planet_column.Width = 90;
                planet_column.MaxDropDownItems = 3;
                planet_column.FlatStyle = FlatStyle.Flat;
                planet_column.DataSource = new List<Planet>(galaxy.Planets);
                //planet_column.DataSource = planet_list;
                //planet_column.DataPropertyName = "Name";
                planet_column.ValueMember = "Name";
                //planet_column.ValueType = typeof(PlanetItem);
                planet_column.DisplayMember = "Name";

            }
            trade_list_view.Columns.Add(planet_column);

            // Bez tego pojawia sie blad bez sensu
            trade_list_view.DataError += new DataGridViewDataErrorEventHandler(trade_list_view_DataError);

            {
                DataGridViewTextBoxColumn free_space_column = new DataGridViewTextBoxColumn();
                free_space_column.HeaderText = "Free space";
                free_space_column.Name = free_space_column.HeaderText;
                free_space_column.Width = 90;
                free_space_column.ValueType = typeof(int);
                free_space_column.SortMode = DataGridViewColumnSortMode.NotSortable;
                free_space_column.ReadOnly = true;
                free_space_column.DefaultCellStyle.BackColor = Color.LightGray;
                //merch_column.DefaultCellStyle.NullValue = "0";
                trade_list_view.Columns.Add(free_space_column);
            }

            HashSet<Merch> wares_involved = trade_route.GetWaresInvolved();

            Dictionary<Merch, int> ware_to_column = new Dictionary<Merch, int>();
            int col = first_ware_col_idx;
            foreach (Merch ware in wares_involved)
            {
                AddMerchColumn(ware.Name);
                ware_to_column[ware] = col;
                col++;
            }

            foreach (TradeRoute.Element el in trade_route.Path)
            {
                int row_no = trade_list_view.Rows.Add(1);
                trade_list_view[planet_col_idx, row_no].Value = el.Planet.Name;
                foreach (KeyValuePair<Merch, int> ware_val in el.Deals)
                {
                    trade_list_view[ware_to_column[ware_val.Key], row_no].Value = ware_val.Value;
                }
            }

            SetMerchColumnColors();
            SetFreeSpace();

        }

        void trade_list_view_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Console.WriteLine("TODO:trade_list_view_DataError: Corect the error");
        }


        private void CreateTradeRoute_Load(object sender, EventArgs e)
        {

        }

        private Dictionary<int, Merch> GetColumnToWares()
        {
            var wares = new Dictionary<int, Merch>();
            foreach (DataGridViewColumn col in trade_list_view.Columns)
            {
                if(col.Index<first_ware_col_idx)
                {
                    continue;
                }
                var result = Merch.GoodsByName_slow(col.Name);//from w in Merch.Goods where w.Name == col.Name select w;
                wares.Add(col.Index, result);

            }
            return wares;
        }

        private void trade_list_view_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == planet_col_idx)
            {
                Planet pla = galaxy.PlanetsByName[trade_list_view[0, e.RowIndex].Value as string];
                //Console.WriteLine(trade_list_view[0, e.RowIndex].Value.ToString());
                //PlanetItem planet_info = (PlanetItem)trade_list_view[0, e.RowIndex].Value;
                //Console.WriteLine(planet_info.planet);
                var dialog_planet = new PlanetDetailsForm(pla);
                dialog_planet.Show();
            }
        }

        private void add_button_Click(object sender, EventArgs e)
        {
            string ware=merch_listBox.SelectedValue as string;
            AddMerchColumn(ware);

        }

        private void AddMerchColumn(string merch)
        {
            foreach (DataGridViewColumn col in trade_list_view.Columns)
            {
                if (col.Name == merch)
                {
                    return;
                }
            }

            DataGridViewTextBoxColumn merch_column=new DataGridViewTextBoxColumn();
            merch_column.HeaderText = merch;
            merch_column.Name = merch_column.HeaderText;
            merch_column.Width = 90;
            merch_column.ValueType = typeof(int);
            merch_column.SortMode = DataGridViewColumnSortMode.NotSortable;
            //merch_column.DefaultCellStyle.NullValue = "0";
            int col_index=trade_list_view.Columns.Add(merch_column);

            foreach (DataGridViewRow row in trade_list_view.Rows)
            {
                row.Cells[col_index].Value = "0";
            }

            SetMerchColumnColors();
            SetFreeSpace();


        }

        private void SetFreeSpace()
        {
            foreach (DataGridViewRow row in trade_list_view.Rows)
            {
                SetFreeSpaceRow(row);
            }
        }

        private void SetFreeSpaceRow(DataGridViewRow row)
        {
            if (row.IsNewRow)
                return;
            int free_space = cargo_space - SumCargoInRow(row);
            row.Cells[free_space_col_idx].Value = free_space.ToString();
        }

        private int SumCargoInRow(DataGridViewRow row)
        {
            int sum = 0;
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.ColumnIndex < first_ware_col_idx)
                    continue;
                sum += Convert.ToInt32(cell.Value.ToString());
            }
            return sum;
        }

        private void SetMerchColumnColors()
        {
            Dictionary<int, Merch> col_to_ware = GetColumnToWares();

            foreach (DataGridViewRow row in trade_list_view.Rows)
            {
                int row_idx=row.Index;
                Planet planeta=null;

                if (trade_list_view[planet_col_idx,row_idx].Value != null)
                {
                        string planet_name = row.Cells[planet_col_idx].Value as string;
                        planeta = galaxy.PlanetsByName[planet_name];
                }

                foreach (KeyValuePair<int, Merch> elem in col_to_ware)
                {
                    int col_idx=elem.Key;

                    Color text_color = Color.LightGray;
                    if(planeta!=null)
                    {
                        Merch ware = Merch.GoodsByName_slow(trade_list_view.Columns[col_idx].HeaderText);
                        
                        if (planeta.store.Purchases(ware))
                            text_color = Color.OrangeRed;
                        if (planeta.store.Offers(ware))
                            text_color = Color.Navy;
                    }

                    trade_list_view[col_idx,row_idx].Style.ForeColor = text_color;
                }
            }
        }

        private void trade_list_view_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= first_ware_col_idx)
            {
                string col_name = trade_list_view.Columns[e.ColumnIndex].Name;
                Console.WriteLine(col_name);
                var result = MessageBox.Show("Are you sure you want do delete the column "+col_name+"?", "Delete column", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result == DialogResult.OK)
                {
                    trade_list_view.Columns.Remove(col_name);
                    SetFreeSpace();
                }
            }
        }

        private void merch_listBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string ware=merch_listBox.SelectedValue as string;
            AddMerchColumn(ware);
        }

        private void button_finish_Click(object sender, EventArgs e)
        {
            if(trade_list_view.Rows.Count<2)
            {
                this.Close();
                return;
            }

            foreach (DataGridViewRow row in trade_list_view.Rows)
            {
                if (row.IsNewRow)
                    continue;

                if (row.Cells[planet_col_idx].Value == null)
                {
                    MessageBox.Show("All planets must be chosen", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            trade_route.Clear();

            var wares = new Dictionary<int, Merch>();
            foreach (DataGridViewColumn col in trade_list_view.Columns)
            {
                if (col.Index<first_ware_col_idx)
                {
                    continue;
                }
                var result = from w in Merch.Goods where w.Name == col.Name select w;
                try
                {
                    //Console.WriteLine(result.ElementAt(0).ToString());
                    wares.Add(col.Index, result.ElementAt(0) as Merch);

                }
                catch (ArgumentOutOfRangeException)
                {
                    Console.WriteLine("Error: No such ware: " + col.Name);
                }

            }

            //var current_row_cargo = new Dictionary<Merch, int>();
            //{
            //    int row_no = trade_list_view.Rows.Count-1;
            //    if (trade_list_view.Rows[row_no].IsNewRow)
            //    {
            //        row_no--;
            //    }
            //    var row = trade_list_view.Rows[row_no];
            //    for (int i = 1; i < trade_list_view.Columns.Count; i++)
            //    //foreach (Merch ware in wares.Values)
            //    {
            //        Merch ware = wares[i];
            //        int value = Convert.ToInt32(row.Cells[i].Value.ToString());
            //        //trade_list.Add(ware, value);
            //        current_row_cargo[ware] = value;
            //    }
            //}

            foreach (DataGridViewRow row in trade_list_view.Rows)
            {
                if (row.IsNewRow)
                    continue;

                var trade_list = new Dictionary<Merch, int>();


                Planet pla = galaxy.PlanetsByName[row.Cells[planet_col_idx].Value as string];
                for (int i = first_ware_col_idx; i < trade_list_view.Columns.Count; i++)
                {
                    //Console.WriteLine(row.Cells[i].Value.GetType().ToString());
                    //Console.WriteLine(row.Cells[i].Value.ToString());
                    Merch ware = wares[i];
                    int value = Convert.ToInt32(row.Cells[i].Value.ToString());
                    //trade_list.Add(ware, value);
                    //trade_list[ware] = value - current_row_cargo[ware];
                    trade_list[ware] = value;
                    //current_row_cargo[ware] = value;
                }

                trade_route.Add(pla, trade_list);
            
            }
            //Console.WriteLine("TR done");
            this.Close();

        }

        private void trade_list_view_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string headerText = trade_list_view.Columns[e.ColumnIndex].HeaderText;
            DataGridViewRow row=trade_list_view.Rows[e.RowIndex];

            if (row.IsNewRow)
            {
                return;
            }

            if (e.ColumnIndex == planet_col_idx)
            {
            }
            else if (e.ColumnIndex >= first_ware_col_idx)
            {
                int wartosc;
                string value = e.FormattedValue as string;
                bool is_number=int.TryParse(value, out wartosc);
                if (is_number)
                {
                    if (wartosc < 0)
                    {
                        row.ErrorText = "Quantity cannot be negative";
                        e.Cancel = true;
                    }
                    else
                    {
                        int stara_wartosc=Convert.ToInt32(row.Cells[e.ColumnIndex].Value.ToString());
                        int nowa_suma=SumCargoInRow(row) - stara_wartosc + wartosc;

                        if (nowa_suma>cargo_space)
                        {
                            row.ErrorText = "Not enough cargo space";
                            e.Cancel = true;
                        }
                    }
                }
                else
                {
                    trade_list_view.Rows[e.RowIndex].ErrorText = "Not a number";
                    e.Cancel = true;
                }
            }
        }

        private void trade_list_view_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var row=trade_list_view.Rows[e.RowIndex];
            row.ErrorText = String.Empty;

            if (e.ColumnIndex == planet_col_idx)
            {
                SetMerchColumnColors();
            }
            else if (e.ColumnIndex >= first_ware_col_idx)
            {
                SetFreeSpaceRow(row);
            }
        }

        private void trade_list_view_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            int col_count = trade_list_view.Columns.Count;
            int row_index = e.RowIndex;

            for (int col_index = first_ware_col_idx; col_index < col_count; col_index++)
            {
                if (trade_list_view[col_index, row_index].Value == null)
                {
                    trade_list_view[col_index, row_index].Value = "0";
                }
            }
            SetMerchColumnColors();
            SetFreeSpace();
        }
        
    }
}
